<template>
	<view class="container">


		<!-- 头部轮播 -->
		<view class="carousel-section">
			<!-- 标题栏和状态栏占位符 -->
			<view class="titleNview-placing"></view>
			<!-- 背景色区域 -->
			<!-- <view class="titleNview-background" :style="{backgroundColor:titleNViewBackground}"></view> -->
			<swiper class="carousel" circular @change="swiperChange" :autoplay="true">
				<swiper-item v-for="(item, index) in carouselList" :key="index" class="carousel-item" @click="navToLink(item)">
					<image :src="item.image" />
				</swiper-item>
			</swiper>
			<!-- 自定义swiper指示器 -->
			<view class="swiper-dots">
				<text class="num">{{swiperCurrent+1}}</text>
				<text class="sign">/</text>
				<text class="num">{{carouselList.length}}</text>
			</view>
		</view>

		<!-- 广告 -->
		<view class="ad-1" v-if="adList.length" @click="navToLink(adList[0])">
			<image :src="adList[0].image" mode="scaleToFill"></image>
		</view>

		<view class="mp-search-box">
			<input class="ser-input" type="text" placeholder="输入关键字查找最适合的话术" @confirm="submit" />
		</view>
		<view class="content">
			<scroll-view class="msg-list" scroll-y="true" :scroll-with-animation="scrollAnimation" :scroll-top="scrollTop"
			 :scroll-into-view="scrollToView">
				<view class="row" v-for="(row,index) in msgList" :key="index" :id="'msg'+row.id">
					<!-- 自己发出的消息 -->
					<view class="my" v-if="row.uid==myuid">
						<view class="left">
							<view v-if="row.type=='text'" class="bubble" @tap="docopy(row)">
								<rich-text :nodes="row.msg.content"></rich-text>
							</view>
							<view v-if="row.type=='voice'" class="bubble voice" @tap="playVoice(row)" :class="playMsgid == row.id?'play':''">
								<view class="length">{{row.msg.length}}</view>
								<view class="icon my-voice"></view> 
							</view>
							<view v-if="row.type=='img'" class="bubble img" @tap="showPic(row)">
								<image :src="row.msg.url" :style="{'width': row.msg.w+'px','height': row.msg.h+'px'}"></image>
							</view>
						</view>
						<view class="right">
							<image src="../../static/kefu3.png"></image>
						</view>
					</view>
					<!-- 别人发出的消息 -->
					<view class="other" v-if="row.uid!=myuid">
						<view class="left">
							<image src="../../static/kefu3.png"></image>
						</view>
						<view class="right">
							<view class="username">
								<view class="name">{{row.username}}</view>
								<view class="time">{{row.time}}</view>
							</view>
							<view v-if="row.type=='text'" class="bubble">
								<rich-text :nodes="row.msg.content"></rich-text>
							</view>
							<view v-if="row.type=='voice'" class="bubble voice" @tap="playVoice(row)" :class="playMsgid == row.id?'play':''">
								<view class="icon other-voice"></view>
								<view class="length">{{row.msg.length}}</view>
							</view>
							<view v-if="row.type=='img'" class="bubble img" @tap="showPic(row)">
								<image :src="row.msg.url" :style="{'width': row.msg.w+'px','height': row.msg.h+'px'}"></image>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

	</view>
</template>

<script>
	import {
		mapActions,
		mapState
	} from 'vuex'
	// import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';  
	export default {
		// components: {
		// 	grouponBox
		// },
		data() {
			return {
				titleNViewBackground: '',
				swiperCurrent: 0,
				carouselList: [],
				navList: [],
				goodsList: [],
				adList: [],
				data: {},
				kw: '',
				goodids: '',
				options: {},
				page: 1,
				loadingType: 'more', //加载更多状态
				filterIndex: 0,
				cat_id: 0, //已选三级分类id 

				//文字消息

				textMsg: '',
				//消息列表
				scrollAnimation: false,
				scrollTop: 0,
				scrollToView: '',
				msgList: [],
				msgImgList: [],
				myuid: 0,
				//录音相关参数
				// #ifndef H5
				//H5不能录音
				RECORDER: uni.getRecorderManager(),
				// #endif
				isVoice: false,
				voiceTis: '按住 说话',
				recordTis: "手指上滑 取消发送",
				recording: false,
				willStop: false,
				initPoint: {
					identifier: 0,
					Y: 0
				},
				recordTimer: null,
				recordLength: 0,
				//播放语音相关参数
				AUDIO: uni.createInnerAudioContext(),
				playMsgid: null,
				VoiceTimer: null,
				//表情定义
				showEmji: '',
			};
		},

		onLoad(options) {
			this.kw = options.kw || '';
			this.init();
			// this.getMsgList();
			this.loadData();

		},
		computed: {},
		methods: {
			...mapActions(['SAVE_HOME_PRODUCTS']),
			//加载商品 ，带下拉刷新和上滑加载
			async loadData() {

				let form = {
					key: this.kw
				}
				var res = await this.$http.get('getword', form);
				// 获取消息中的图片,并处理显示尺寸
				var list=res.data;
				for (let i = 0; i < list.length; i++) {
					if (list[i].type == 'img') {
						list[i] = this.setPicSize(list[i]);
						console.log("list[i]: " + JSON.stringify(list[i]));
						this.msgImgList.push(list[i].msg.url);
					}
				}
				this.msgList = list;
			},
			docopy(row){
				//点击复制消息
				uni.setClipboardData({
				    data: row.msg.content,
				    success: function () {
				        console.log('success');
						uni.showToast({
							title:'复制成功'
						})
				    }
				});
			}, 
			getHomeProducts() {
				this.$http.get('home.products').then(res => {
					this.data = res.data
				}).catch(e => {})
			},
			init() {
				// return Promise.all([this.getHomeProducts(), this.getNavData()])
				return Promise.all([this.getNavData()])
			},
			getNavData() {
				this.$http.post('nav', {
					nav_type: [0, 1, 2]
				}).then(res => {
					this.carouselList = res.data[0] || []
					this.navList = res.data[1] || []
					this.adList = res.data[2] || []
					this.titleNViewBackground = this.carouselList[0] ? (this.carouselList[0].params ? (this.carouselList[0].params[
						'color'] || '') : '') : ''
				})
			},
			goCategory() {
				uni.switchTab({
					url: '/pages/category/category'
				})
			},
			goGroupCategory(item) {
				uni.navigateTo({
					url: '/pages/product/list?groupon=1'
				})
			},
			//轮播图切换修改背景色
			swiperChange(e) {
				const index = e.detail.current;
				this.swiperCurrent = index;
				this.titleNViewBackground = this.carouselList[index].params ? (this.carouselList[index].params.color || '') : ''
			},
			navToDetailPage(item) {
				uni.navigateTo({
					url: '/pages/product/product?id=' + item.id
				})
			},
			navToLink(item) {
				this.$meRouter(item)
			},
			submit(e) {
				uni.navigateTo({
					url: '/pages/cdetail/cdetail?kw=' + e.detail.value
				})
				// this.goSearch(e.detail.value)
			},
			goSearch(kw) {
				uni.navigateTo({
					url: '/pages/product/list?kw=' + kw
				})
			},
			getMsgList() {
				// 消息列表
				let list = [{
						id: 0,
						uid: 0,
						username: "大黑哥",
						face: "/static/img/face.jpg",
						time: "12:56",
						type: "text",
						msg: {
							content: "这个是有偏差的，两个温度相差十几二十度是很正常的，如果相差五十度，那即是质量问题了。"
						}
					},
					{
						id: 0,
						uid: 0,
						username: "大黑哥",
						face: "/static/img/face.jpg",
						time: "12:56",
						type: "text",
						msg: {
							content: "这个是有偏差的，两个温度相差十几二十度是很正常的，如果相差五十度，那即是质量问题了。"
						}
					},
					{
						id: 0,
						uid: 0,
						username: "大黑哥",
						face: "/static/img/face.jpg",
						time: "12:56",
						type: "text",
						msg: {
							content: "这个是有偏差的，两个温度相差十几二十度是很正常的，如果相差五十度，那即是质量问题了。"
						}
					},
					{
						id: 0,
						uid: 0,
						username: "大黑哥",
						face: "/static/img/face.jpg",
						time: "12:56",
						type: "text",
						msg: {
							content: "这个是有偏差的，两个温度相差十几二十度是很正常的，如果相差五十度，那即是质量问题了。"
						}
					},
					{
						id: 0,
						uid: 0,
						username: "大黑哥",
						face: "/static/img/face.jpg",
						time: "12:56",
						type: "text",
						msg: {
							content: "这个是有偏差的，两个温度相差十几二十度是很正常的，如果相差五十度，那即是质量问题了。"
						}
					},
					{
						id: 0,
						uid: 0,
						username: "大黑哥",
						face: "/static/img/face.jpg",
						time: "12:56",
						type: "text",
						msg: {
							content: "这个是有偏差的，两个温度相差十几二十度是很正常的，如果相差五十度，那即是质量问题了。"
						}
					},
					// {
					// 	id: 3,
					// 	uid: 0,
					// 	username: "大黑哥",
					// 	face: "/static/img/face.jpg",
					// 	time: "13:05",
					// 	type: "voice",
					// 	msg: {
					// 		url: "/static/voice/2.mp3",
					// 		length: "00:06"
					// 	}
					// }, 

				]
				// 获取消息中的图片,并处理显示尺寸
				for (let i = 0; i < list.length; i++) {
					if (list[i].type == 'img') {
						list[i] = this.setPicSize(list[i]);
						console.log("list[i]: " + JSON.stringify(list[i]));
						this.msgImgList.push(list[i].msg.url);
					}
				}
				this.msgList = list;
				// 滚动到底部
				// this.$nextTick(function() {
				// 	this.scrollTop = 9999;
				// 	this.scrollAnimation = true;
				// });
			},
			//处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
			setPicSize(row) {
				let maxW = uni.upx2px(350);
				let maxH = uni.upx2px(350);
				if (row.msg.w > maxW || row.msg.h > maxH) {
					let scale = row.msg.w / row.msg.h;
					if (row.msg.w > row.msg.h) {
						row.msg.w = maxW;
						row.msg.h = row.msg.w / scale
					} else {
						row.msg.h = maxH;
						row.msg.w = row.msg.h * scale;
					}
				}
				return row;
			},
			// 接受消息(筛选处理)
			screenMsg(msg) {
				//从长连接处转发给这个方法，进行筛选处理
				if (msg.uid != this.myuid) {
					uni.vibrateLong();
				}
				switch (msg.type) {
					case 'text':
						this.addTextMsg(msg);
						break;
					case 'voice':
						this.addVoiceMsg(msg);
						break;
					case 'img':
						this.addImgMsg(msg);
						break;
				}
				this.$nextTick(function() {
					this.scrollToView = 'msg' + msg.id
				});
			},
			// 选择表情
			chooseEmoji() {
				this.showEmji = this.showEmji == 'showEmoji' ? 'hideEmoji' : 'showEmoji';
			},
			// 隐藏表情
			hideEmoji() {
				this.showEmji = this.showEmji == 'showEmoji' ? 'hideEmoji' : '';
			},
			//添加表情
			addEmoji(em) {
				this.textMsg += em.alt;
			},
			// 发送文字消息
			sendText() {
				this.hideEmoji();
				if (!this.textMsg) {
					return;
				}
				let content = this.replaceEmoji(this.textMsg);
				let msg = {
					content: content
				}
				this.sendMsg(msg, 'text');
				this.textMsg = '';
			},
			//替换表情符号为图片
			replaceEmoji(str) {
				let replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g, (item, index) => {
					console.log("item: " + item);
					for (let i = 0; i < this.emojiList.length; i++) {
						let row = this.emojiList[i];
						for (let j = 0; j < row.length; j++) {
							let EM = row[j];
							if (EM.alt == item) {
								//在线表情路径，图文混排必须使用网络路径
								let onlinePath = 'https://s2.ax1x.com/2019/04/12/'
								let imgstr = '<img src="' + onlinePath + this.onlineEmoji[EM.url] + '">';
								console.log("imgstr: " + imgstr);
								return imgstr;
							}
						}
					}
				});
				return '<div style="display: flex;align-items: center;">' + replacedStr + '</div>';
			},
			// 选择图片发送
			chooseImage() {
				this.hideEmoji();
				uni.chooseImage({
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res) => {
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							uni.getImageInfo({
								src: res.tempFilePaths[i],
								success: (image) => {
									console.log(image.width);
									console.log(image.height);
									let msg = {
										url: res.tempFilePaths[i],
										w: image.width,
										h: image.height
									};
									this.sendMsg(msg, 'img');
								}
							});
						}
					}
				});
			},
			// 发送消息
			sendMsg(content, type) {
				//实际应用中，此处应该提交长连接，模板仅做本地处理。
				var nowDate = new Date();
				let lastid = this.msgList[this.msgList.length - 1].id;
				lastid++;
				let msg = {
					id: lastid,
					uid: 0,
					username: "大黑哥",
					face: "/static/img/face.jpg",
					time: nowDate.getHours() + ":" + nowDate.getMinutes(),
					type: type,
					msg: content
				};
				this.screenMsg(msg);
				// 定时器模拟对方回复,三秒
				setTimeout(() => {
					lastid = this.msgList[this.msgList.length - 1].id;
					lastid++;
					msg = {
						id: lastid,
						uid: 1,
						username: "售后客服008",
						face: "/static/img/im/face/face_2.jpg",
						time: nowDate.getHours() + ":" + nowDate.getMinutes(),
						type: type,
						msg: content
					};
					this.screenMsg(msg);
				}, 3000)
			},

			// 处理文字消息
			addTextMsg(msg) {
				this.msgList.push(msg);
			},
			// 处理语音消息
			addVoiceMsg(msg) {
				this.msgList.push(msg);
			},
			// 处理图片消息
			addImgMsg(msg) {
				msg = this.setPicSize(msg);
				this.msgImgList.push(msg.msg.url);
				this.msgList.push(msg);
			},
			// 预览图片
			showPic(row) {
				console.log(this.msgImgList)
				uni.previewImage({
					indicator: "none",
					current: row.msg.url,
					urls: this.msgImgList
				});
			},
			// 播放语音
			playVoice(msg) {
				this.playMsgid = msg.id;
				this.AUDIO.src = msg.msg.url;
				console.log("msg.msg.url: " + msg.msg.url);
				this.AUDIO.play();
			},
			// 录音开始
			voiceBegin(e) {
				if (e.touches.length > 1) {
					return;
				}
				this.initPoint.Y = e.touches[0].clientY;
				this.initPoint.identifier = e.touches[0].identifier;
				this.RECORDER.start({
					format: "aac"
				}); //录音开始,
			},
			//录音开始UI效果
			recordBegin(e) {
				this.recording = true;
				this.voiceTis = '松开 结束';
				this.recordLength = 0;
				this.recordTimer = setInterval(() => {
					this.recordLength++;
				}, 1000)
			},
			// 录音被打断
			voiceCancel() {
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.willStop = true; //不发送录音
				this.RECORDER.stop(); //录音结束
			},
			// 录音中(判断是否触发上滑取消发送)
			voiceIng(e) {
				if (!this.recording) {
					return;
				}
				let touche = e.touches[0];
				//上滑一个导航栏的高度触发上滑取消发送
				if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
					this.willStop = true;
					this.recordTis = '松开手指 取消发送'
				} else {
					this.willStop = false;
					this.recordTis = '手指上滑 取消发送'
				}
			},
			// 结束录音
			voiceEnd(e) {
				if (!this.recording) {
					return;
				}
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.RECORDER.stop(); //录音结束
			},

			//录音结束(回调文件)
			recordEnd(e) {
				clearInterval(this.recordTimer);
				if (!this.willStop) {
					plus.io.resolveLocalFileSystemURL(e.tempFilePath, function(entry) {
						// 可通过entry对象操作test.html文件 
						entry.file(function(file) {
							console.log(file.size + '--' + file.name);
						});
					}, function(e) {
						alert("Resolve file URL failed: " + e.message);
					});
					console.log("e: " + JSON.stringify(e));
					let msg = {
						length: 0,
						url: e.tempFilePath
					}
					let min = parseInt(this.recordLength / 60);
					let sec = this.recordLength % 60;
					min = min < 10 ? '0' + min : min;
					sec = sec < 10 ? '0' + sec : sec;
					msg.length = min + ':' + sec;
					this.sendMsg(msg, 'voice');
				} else {
					console.log('取消发送录音');
				}
				this.willStop = false;
			},
			// 切换语音/文字输入
			switchVoice() {
				this.hideEmoji();
				this.isVoice = this.isVoice ? false : true;
			},
			discard() {
				return;
			}

		},
		// #ifndef MP
		// 标题栏input搜索框点击
		/* onNavigationBarSearchInputClicked: function(e) {
			console.log(e)
		}, */
		onNavigationBarSearchInputConfirmed: function(e) {
			this.goSearch(e.text)
		},
		//点击导航栏 buttons 时触发
		onNavigationBarButtonTap(e) {
			const index = e.index;
			if (index === 0) {
				/// this.$api.msg('点击了扫描');
				// 允许从相机和相册扫码
				uni.scanCode({
					success: function(res) {
						console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);
					}
				});
			} else if (index === 1) {
				return false
				// #ifdef APP-PLUS
				const pages = getCurrentPages();
				const page = pages[pages.length - 1];
				const currentWebview = page.$getAppWebview();
				currentWebview.hideTitleNViewButtonRedDot({
					index
				});
				// #endif
				uni.navigateTo({
					url: '/pages/notice/notice'
				})
			}
		},
		// #endif

		onPullDownRefresh() {
			this.init().then(e => {
				uni.stopPullDownRefresh()
			}).catch(e => {
				uni.stopPullDownRefresh()
			})
		},

	}
</script>

<style lang="scss">
	page {
		.cate-section {
			position: relative;
			z-index: 5;
			border-radius: 16upx 16upx 0 0;
			margin-top: -20upx;
		}

		.carousel-section {
			padding: 0;

			.titleNview-placing {
				padding-top: 0;
				height: 0;
			}

			.carousel {
				.carousel-item {
					padding: 0;
				}
			}

			.swiper-dots {
				left: 45upx;
				bottom: 40upx;
			}
		}
	}




	page {
		background: $page-color-base;
	}

	.m-t {
		margin-top: 16upx;
	}

	/* 头部 轮播图 */
	.carousel-section {
		position: relative;
		padding-top: 10px;

		.titleNview-placing {
			height: var(--status-bar-height);
			padding-top: 44px;
			box-sizing: content-box;
		}

		.titleNview-background {
			position: absolute;
			top: 0;
			left: 0;
			z-index: -99;
			width: 100%;
			height: 400rpx;
			transition: .4s;
		}
	}

	.carousel {
		width: 100%;
		height: 450rpx;

		.carousel-item {
			width: 100%;
			height: 100%;
			padding: 0 14rpx;
			overflow: hidden;
		}

		image {
			width: 100%;
			height: 100%;
			border-radius: 10upx;
		}
	}

	.mp-search-box {
		position: relative; 
		width: 100%;
		padding: 5px 25px;
		// background: darkturquoise;

		.ser-input {
			flex: 1;
			height: 100upx;
			line-height: 50upx;
			text-align: center;
			font-size: 32upx;
			color: $font-color-base;
			border-radius: 35px;
			background: rgba(255, 255, 255, .8);
		}
	}

	.swiper-dots {
		display: flex;
		position: absolute;
		left: 60upx;
		bottom: 15upx;
		width: 72upx;
		height: 36upx;
		background-image: url();
		background-size: 100% 100%;

		.num {
			width: 36upx;
			height: 36upx;
			border-radius: 50px;
			font-size: 24upx;
			color: #fff;
			text-align: center;
			line-height: 36upx;
		}

		.sign {
			position: absolute;
			top: 0;
			left: 50%;
			line-height: 36upx;
			font-size: 12upx;
			color: #fff;
			transform: translateX(-50%);
		}
	}

	/* 分类 */
	.cate-section {
		display: flex;
		justify-content: space-around;
		align-items: center;
		flex-wrap: wrap;
		padding: 30upx 22upx;

		.cate-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			font-size: $font-sm + 2upx;
			color: $font-color-dark;
		}

		/* 原图标颜色太深,不想改图了,所以加了透明度 */
		image {
			width: 88upx;
			height: 88upx;
			margin-bottom: 14upx;
			border-radius: 50%;
			// opacity: .7;
			// box-shadow: 4upx 4upx 20upx rgba(250, 67, 106, 0.3);
		}
	}

	/* 图片导航 */
	.picdd {
		display: -webkit-box;
		margin-top: 6px;

		.pic-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			font-size: $font-sm + 2upx;
			color: $font-color-dark;
			width: 50%;
			height: 470rpx;

			image {
				width: 100%;

			}
		}
	}

	.ad-1 {
		width: 100%;
		height: 210upx;
		padding: 10upx 0;
		background: $page-color-light;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.content {
		width: 100%;

		.msg-list {
			width: 96%;
			position: relative;

			.row {
				// &:first-child {
				// 	margin-top: 20upx;
				// }

				padding: 20upx 0;

				.my .left,
				.other .right {
					width: 100%;
					display: flex;

					.bubble {
						max-width: 85%;
						min-height: 50upx;
						border-radius: 10upx;
						padding: 15upx 20upx;
						display: flex;
						align-items: center;
						font-size: 32upx;
						word-break: break-word;

						&.img {
							background-color: transparent;
							padding: 0;
							overflow: hidden;

							image {
								max-width: 350upx;
								max-height: 350upx;
								border-radius: 30upx;
							}
						}

						&.voice {
							.icon {
								font-size: 40upx;
								display: flex;
								align-items: center;
							}

							.icon:after {
								content: " ";
								width: 53upx;
								height: 53upx;
								border-radius: 100%;
								position: absolute;
								box-sizing: border-box;
							}

							.length {
								font-size: 28upx;
							}
						}
					}
				}

				.my .right,
				.other .left {
					flex-shrink: 0;
					width: 80upx;
					height: 80upx;

					image {
						width: 80upx;
						height: 80upx;
						border-radius: 60upx;
					}
				}

				.my {
					width: 100%;
					display: flex;
					justify-content: flex-end;

					.left {
						min-height: 80upx;

						align-items: center;
						justify-content: flex-end;

						.bubble {
							background-color: #6cd2f0;
							color: #fff;

							&.voice {
								.icon {
									color: #fff;
								}

								.length {
									margin-right: 20upx;
								}
							}

							&.play {
								@keyframes my-play {
									0% {
										transform: translateX(80%);
									}

									100% {
										transform: translateX(0%);
									}
								}

								.icon:after {
									border-left: solid 10upx rgba(240, 108, 122, .5);
									animation: my-play 1s linear infinite;
								}
							}
						}
					}

					.right {
						margin-left: 15upx;
					}
				}

				.other {
					width: 100%;
					display: flex;

					.left {
						margin-right: 15upx;
					}

					.right {
						flex-wrap: wrap;

						.username {
							width: 100%;
							height: 45upx;
							font-size: 24upx;
							color: #999;
							display: flex;

							.name {
								margin-right: 50upx;
							}
						}

						.bubble {
							background-color: #fff;
							color: #333;

							&.voice {
								.icon {
									color: #333;

								}

								.length {
									margin-left: 20upx;
								}
							}

							&.play {
								@keyframes other-play {
									0% {
										transform: translateX(-80%);
									}

									100% {
										transform: translateX(0%);
									}
								}

								.icon:after {
									border-right: solid 10upx rgba(255, 255, 255, .8);

									animation: other-play 1s linear infinite;
								}
							}
						}
					}
				}
			}
		}
	}
</style>
